package com.cqit.bluetoothkeybox.utils;

import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.util.Random;

/**
 * 发送短信工具
 */
@Component
@Validated
@Slf4j
public class SmsMessageUtil {
    @Value("${sms.url}")
    private String url;
    @Value("${sms.uid}")
    private String uid;
    @Value("${sms.key}")
    private String key;

    @Value("${aliyun-sms.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun-sms.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 短信通
     * * UTF-8编码发送接口地址：
     * * http://utf8.api.smschinese.cn/?Uid=本站用户名&Key=接口安全秘钥&smsMob=手机号码&smsText=验证码:8888
     * 发送验证码，由你自己决定内容
     *
     * @param mobile  发送人手机号码
     * @param smsText 短信内容
     * @return 发送状态（大于0表示，发送成功的数量）
     */
    public Integer sendMessage(@NotBlank(message = "手机号码不能为空") @Size(min = 11, max = 11, message = "手机号码长度只能为11位") String mobile,
                               @Size(max = 64, message = "短信内容过长，可能另外收费，最好不要超过64位！") String smsText) throws IOException {

        HttpPost httpPost = new HttpPost(this.url + "?Uid=" + this.uid + "&Key=" + this.key + "&smsMob=" + mobile + "&smsText=" + getRandomCode(6));
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            if (response != null) {
                return Integer.parseInt(EntityUtils.toString(response.getEntity(), Consts.UTF_8));
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("短信发送失败");
        } finally {
            if (null != response) {
                response.close();
            }
            httpClient.close();
        }
        return 0;
    }


    public com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public String getMessage(Integer code) {
        String message;
        if (code > 0) {
            message = "SMS-f发送成功！短信量还有" + code + "条";
        } else if (code == -1) {
            message = "SMS-没有该用户账户";
        } else if (code == -2) {
            message = "SMS-接口密钥不正确";
        } else if (code == -21) {
            message = "SMS-MD5接口密钥加密不正确";
        } else if (code == -3) {
            message = "SMS-短信数量不足";
        } else if (code == -11) {
            message = "SMS-该用户被禁用";
        } else if (code == -14) {
            message = "SMS-短信内容出现非法字符";
        } else if (code == -4) {
            message = "SMS-手机号格式不正确";
        } else if (code == -41) {
            message = "SMS-手机号码为空";
        } else if (code == -42) {
            message = "SMS-短信内容为空";
        } else if (code == -51) {
            message = "SMS-短信签名格式不正确接口签名格式为：【签名内容】";
        } else if (code == -6) {
            message = "SMS-IP限制";
        } else {
            message = "其他错误";
        }
        return message;
    }

    /**
     * 随机生成 length位验证码
     *
     * @param length 位数
     * @return 验证码
     */
    public String getRandomCode(Integer length) {
        Random random = new Random();
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < length; i++) {
            result.append(random.nextInt(10));
        }
        return result.toString();
    }
}

